import {reactive, ref, toRaw, toRefs, unref} from "vue";

interface Config<T> {
    api: (listQuery: ListQuery) => Promise<PageInfo<T>>
    listQuery: any
}

/**
 * 手机端分页数据
 */
interface PageState<T> {
    listQuery: ListQuery
    //数据总数
    totalElements: number,
    // 列表数据
    listData: T[],
    // 列表加载状态
    listLoading: boolean,
    //列表刷新状态
    listRefreshing: boolean
    //列表展示完成
    listFinished: boolean
    //列表完成文字
    listFinishedText: string
}

export const usePageableEffect = <T>(api: (listQuery?: any) => Promise<PageInfo<T>>, listQuery = toRefs({})) => {

    const pageState: PageState<T> = reactive({
        listQuery: {
            //当前页码
            currentPage: 1,
            //每页条数
            pageSize: 10,
        },
        //数据总数
        totalElements: 0,
        // 列表数据
        listData: [],
        // 列表加载状态
        listLoading: false,
        //列表刷新状态
        listRefreshing: false,
        //列表展示完成
        listFinished: false,
        listFinishedText: '没有更多了'
    })
    //获取数据
    const fetchData = () => {
        if (!pageState.listRefreshing) {
            pageState.listLoading = true
        }
        api({...pageState.listQuery, ...(toRaw(unref(listQuery)))}).then((pageData) => {
            pageState.listData = [...pageState.listData, ...pageData.dataList]
            pageState.totalElements = pageData.totalCount
            if (pageData.dataList.length < pageState.listQuery.pageSize) {
                pageState.listFinished = true
            }

        }).catch(() => {
            //报错直接完成
            pageState.listFinished = true
        })
            .finally(() => {
                pageState.listLoading = false
                pageState.listRefreshing = false
            })
    }

    //加载时执行
    const onLoadPage = () => {
        if (pageState.listRefreshing) {
            pageState.listRefreshing = false;
        }
        //第一次加载不用加页码
        if (pageState.totalElements > 0) {
            pageState.listQuery.currentPage = pageState.listQuery.currentPage + 1
        }
        fetchData()
    }
    /**
     * 刷新
     * @param listQuery
     */
    const onRefreshPage = (listQuery = {}) => {
        pageState.listData.length = 0
        pageState.listFinished = false
        pageState.listQuery = {...pageState.listQuery, ...listQuery, currentPage: 1}
        fetchData()
    }
    return {...toRefs(pageState), onLoadPage, onRefreshPage}
}
